package com.ecarx.camera.utils;

import static com.ecarx.camera.utils.RadioBtnClickFilterUtils.DEFAULT_DELAY_MS;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 仅用于测试切换摄像头
 *
 * @author : shuliang.zhang
 * @date : 2023/06/09
 */
public class TestSwitchCamera {

    private static final String TAG = "TestSwitchCamera";
    /**
     * TODO need modify to false
     */
    private static final boolean NEED_TEST = false;
    /**
     * TODO need modify to false
     */
    private static final boolean TEST_FOREVER = false;
    private static final int MAX_TEST_COUNT = 300;

    private static final long CHECK_DELAY_MS = DEFAULT_DELAY_MS;

    private static final int MSG_CHECK = 1;

    private static ArrayList<Integer> sCheckIds = new ArrayList<>();
    private static int sCheckIdIndex = 0;
    private static int sTestCount = 0;
    private static RadioGroup sRadioGroup;

    private static Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case MSG_CHECK:
                    sTestCount++;
                    if ((!TEST_FOREVER && MAX_TEST_COUNT < sTestCount) || sRadioGroup == null) {
                        break;
                    }
                    if (sCheckIdIndex >= sCheckIds.size()) {
                        sCheckIdIndex = 0;
                    }
                    int checkId = sCheckIds.get(sCheckIdIndex);
                    LogUtils.d(TAG, "check id:" + checkId + ", testCount:" + sTestCount);
                    sRadioGroup.check(checkId);
                    sCheckIdIndex++;

                    mHandler.removeMessages(MSG_CHECK);
                    mHandler.sendEmptyMessageDelayed(MSG_CHECK, CHECK_DELAY_MS);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 开始测试来回切换摄像头
     * @param radioGroup
     * @param checkIds
     */
    public static void test(RadioGroup radioGroup, Integer... checkIds) {
        if (!NEED_TEST) {
            return;
        }
        if (radioGroup == null || checkIds == null) {
            return;
        }
        sTestCount = 0;
        sCheckIdIndex = 0;
        sCheckIds.clear();
        sCheckIds.addAll(Arrays.asList(checkIds));
        sRadioGroup = radioGroup;

        mHandler.removeMessages(MSG_CHECK);
        mHandler.sendEmptyMessage(MSG_CHECK);
    }

    /**
     * 清除数据
     */
    public static void clear() {
        if (!NEED_TEST) {
            return;
        }
        sTestCount = 0;
        sCheckIdIndex = 0;
        sCheckIds.clear();
        sRadioGroup = null;
        mHandler.removeMessages(MSG_CHECK);
    }
}
